package org.example.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 头像文件控制器
 * 处理头像文件的静态资源访问
 */
@RestController
@RequestMapping("/api/avatars")
@CrossOrigin(origins = "*")
public class AvatarController {

    /**
     * 获取头像文件
     */
    @GetMapping("/{filename}")
    public ResponseEntity<byte[]> getAvatar(@PathVariable String filename) {
        try {
            System.out.println("请求头像文件: " + filename);

            // 尝试绝对路径
            Path currentDir = Paths.get("").toAbsolutePath();
            Path filePath = currentDir.resolve("uploads").resolve("avatars").resolve(filename);

            System.out.println("头像文件完整路径: " + filePath);
            System.out.println("文件是否存在: " + Files.exists(filePath));

            if (!Files.exists(filePath)) {
                System.out.println("头像文件不存在: " + filename);
                return ResponseEntity.notFound().build();
            }

            byte[] imageBytes = Files.readAllBytes(filePath);
            String contentType = Files.probeContentType(filePath);

            System.out.println("头像文件大小: " + imageBytes.length + " bytes");
            System.out.println("Content-Type: " + contentType);

            return ResponseEntity.ok()
                    .header("Content-Type", contentType != null ? contentType : "application/octet-stream")
                    .header("Cache-Control", "max-age=86400") // 缓存24小时
                    .body(imageBytes);

        } catch (IOException e) {
            System.err.println("获取头像失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
